package jhc.cn.servlet;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.dbutils.QueryRunner;



import jhc.cn.AirSpace;
import jhc.cn.bean.Article;
import jhc.cn.db.ArticleDao;

/**
 * Servlet implementation class ListArticles
 */
@WebServlet("/list.do")
public class ListArticles extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String pageNum = request.getParameter("page");
		int currentPage = 0;
		if(pageNum != null) {
			try {
				currentPage = Integer.valueOf(pageNum).intValue();
			} catch (NumberFormatException e1) {
				e1.printStackTrace();
				currentPage = 0;
			}
		}
		
		QueryRunner runner = (QueryRunner) request.getServletContext().getAttribute(AirSpace.KET_QUERY_RUNNER);
		List<Article> articles = null;
		long count = 0;
		try {
			articles = ArticleDao.find(runner, currentPage);
			count = ArticleDao.count(runner);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		long total = //count % AirSpace.PAGE_SIZE == 0 ? count / AirSpace.PAGE_SIZE : 
			count / AirSpace.PAGE_SIZE;
		//request.getSession().setAttribute("articles", articles);
		//response.sendRedirect("./list.jsp");
		
		request.setAttribute("articles", articles);
		request.setAttribute("currentPage", currentPage);
		request.setAttribute("total", total);
		request.getRequestDispatcher("./list.jsp").forward(request, response);
	}

}
